/**
 * 导入模板.
 * @oMetaData  主metadata对象
 * @mmg 表格操作方法对象的集合
 * @dropData 下拉数据
 * @funcId 功能项id
 */
define(function(require, exports,module) {
    require("commonStaticDirectory/plugins/import/import.css"); //css

    require("commonStaticDirectory/plugins/artDialog/ui-dialog.css"); //artDialog弹窗
    require("commonStaticDirectory/plugins/artDialog/dialog-plus");  //artDialog弹窗
    var Ajax = require("js/ajax");
    require("commonStaticDirectory/plugins/dayhrDropSelect/dayhrDropSelect.css");
    var dayhrDropSelect = require("commonStaticDirectory/plugins/dayhrDropSelect/dayhrDropSelect");

    require("commonStaticDirectory/plugins/bootstrap-switch/bootstrap-switch.css");
    require("commonStaticDirectory/plugins/bootstrap-switch/bootstrap-switch");

    var Import = function(){
        this.init.apply(this,arguments);
    };

    Import.prototype = {
        /** 构造函数 */
        constructor: Import,
        /*默认的配置*/
        options:{
            oMetaData:undefined //主metadata对象
            ,mmg:undefined //主表格对象
            ,dropData:undefined //下拉数据
            ,funcId:undefined //功能项id
            ,customParam:undefined //薪酬处理参数
        },
        /**
         * 初始化函数
         * */
        init:function(options){
            var t = this;
            this.options = $.extend({},this.options,options); //合并配置参数
            this.infoSetId = t.options.oMetaData.options.infoSetId;
            this.initDom(); //初始化dom结构
        },
        /**
         * 初始化dom结构
         * */
        initDom:function(){
            var t = this;
            t.d = dialog({
                title: "导入模板",
                fixed: true,
                //注意：metadata.html中的 导入Excel模板的html代码已经删除，其他项目没删除的已作废
                content: '' +
                '   <div class="dayhr_import clearfix">'+
                '        <dl class="dayhr_import_dl clearfix">'+
                '            <dt class="list_number">1</dt>'+
                '            <dt class="list_title"><strong>下载模板</strong><span>请点击按钮下载模板文件，并按照文件格式要求填充数据。</span></dt>'+
                '            <dd>'+
                '                请选择模板格式：'+
                '                <div class="dayhr_drop_select" id="download_excel_templates" data-name="modelId" style="display: inline-block;vertical-align: middle;margin-right: 7px;margin-left: 14px;"></div>'+
                '                <div class="base_import_infomation_show_btn iconfont_dayhr_base">'+
                '                    &#xe603;'+
                '                    <div class="base_import_infomation_show">'+
                '                        说明：当前界面不需要特殊的模板，只要保证导入数据列名能够被系统识别即可。'+
                '                    </div>'+
                '                </div>'+
                '                <div class="operation_templates_description" style="position: relative;">'+
                '                    是否导出已有数据：'+
                '                    <div class="base_export_excel_switch">'+
                '                        <input class="switch-checkbox" name="operationType" id="operation_templates" type="checkbox" data-size="small" />'+
                '                    </div>'+
                '                </div>'+
                '                <input type="button" id="download_excel" class="flat-button flat-medium flat-yellow" value="下载模板"/>'+
                '            </dd>'+
                '        </dl>'+
                '        <dl class="dayhr_import_dl clearfix">'+
                '            <dt class="list_number">2</dt>'+
                '            <dt class="list_title"><strong>上传文件</strong><span>请点击按钮上传填充了要导入数据的模板格式文件。</span></dt>'+
                '            <dd>'+
                '                <div id="upload_file_excel" class="clearfix">'+
                '                    <form id="upload_file_excel_btns" enctype="multipart/form-data" method="post">'+
                '                        <button id="upload_file_excel_selectFile" class="flat-button flat-medium flat-blue">选择文件</button>'+
                '                        <input type="file" name="file" id="upload_file_excel_file"/>'+
                '                        <div class="upload_file_description">'+
                '                            是否依据导入模板删除系统中已有的数据：'+
                '                            <div class="base_export_excel_switch">'+
                '                                <input class="switch-checkbox" name="operationType" id="base_uploadExcel_and_delete" type="checkbox" data-size="small" />'+
                '                            </div>'+
                '                        </div>'+
                '                        <div class="upload_file_description upload_file_description2">'+
                '                            是否覆盖导入：'+
                '                            <div class="base_export_excel_switch">'+
                '                                <input class="switch-checkbox" name="operationType" id="base_uploadExcel_and_update" type="checkbox" data-size="small" />'+
                '                            </div>'+
                '                        </div>'+
                '                        <button id="upload_file_excel_startUpload" class="flat-button flat-medium flat-yellow">开始上传</button>'+
                '                        <input type="text" id="upload_file_excel_input" readonly />'+
                '                    </form>'+
                '                    <!--用来存放文件信息-->'+
                '                    <div id="upload_file_list" class="uploader-list"></div>'+
                '                    <!--屏蔽选择上传-->'+
                '                    <div id="upload_file_btns_disabled"></div>'+
                '                </div>'+
                '            </dd>'+
                '        </dl>'+
                '        <dl class="dayhr_import_dl clearfix">'+
                '            <dt class="list_number">3</dt>'+
                '            <dt class="list_title"><strong>检验数据</strong><span>系统将检验导入文件中相关数据的逻辑是否合理</span></dt>'+
                '            <dd>'+
                '            </dd>'+
                '        </dl>'+
                '        <dl class="dayhr_import_dl clearfix" id="dayhr_import_complete">'+
                '            <dt class="list_number">4</dt>'+
                '            <dt class="list_result">End</dt>'+
                '            <dt class="list_title"><strong>完成操作</strong></dt>'+
                '            <dd>'+
                '            </dd>'+
                '        </dl>'+
                '    </div>'
            });
            t.d.showModal();//模态弹出
            t.initDropSelect(); //初始化下拉框
            t.initSwitch(); //是否控件

            //模板下载
            $("#download_excel").off("click").on("click",function(){
                //判断session是否过期
                Ajax.ApiTools().checkSessionTimeout({
                    success:function(data){
                        if(data.result == "true"){
                            var sOperation = $("#operation_templates").bootstrapSwitch("state")?"delete":"update"; //是否导出已有数据
                            var sModelId = "";
                            if(t.oDrop){
                                sModelId = t.oDrop.getValue();
                            }
                            //如果是码表就多传一个参数ct_set_id
                            var sUrl = (gMain.apiBasePath?gMain.apiBasePath:gMain.basePath) + "route/"+t.infoSetId+"/downloadImportExcel.do?funcId="+ t.options.funcId+"&infoSetId="+ t.options.oMetaData.options.infoSetId+"&modelId="+sModelId+"&operationType="+sOperation+((t.options.oMetaData.options.infoSetId=="ct" && t.options.oMetaData.options.navigationId)?("&ct_set_id="+t.options.oMetaData.options.navigationId):"");
                            //如果列表有导航
                            if(t.options.oMetaData.markGetAllPostData().navigationCondition){
                                sUrl += "&navigationCondition="+JSON.stringify({
                                        key:t.options.oMetaData.markGetAllPostData().navigationCondition.key
                                        ,value:t.options.oMetaData.markGetAllPostData().navigationCondition.value
                                    });
                            }

                            //薪酬处理 特殊传参
                            if(t.infoSetId == 'pay_payroll_list'){
                                t.options.customParam.payment_mark = '0';
                            }
                            if(!$.isEmptyObject(t.options.customParam)){
                                var sCustomParam = JSON.stringify(t.options.customParam);
                                sUrl += "&customParam="+ sCustomParam;
                            }

                            location.href = encodeURI(sUrl);
                        }
                    }
                });
            });
            this.initWebuploader(); //初始化上传控件

            $(".base_import_infomation_show_btn").on("mouseenter",function(){
                $(this).find(".base_import_infomation_show").css({
                    left:$(this).position().left -18 + "px"
                });
            });
        },
        /**
         * 初始化下拉框
         * */
        initDropSelect:function(){
            var t = this;
            //拼装下拉菜单数据
            var aDropData = [];
            if(t.options.dropData && t.options.dropData.maps.length){
                for(var i=0;i<t.options.dropData.maps.length;i++){
                    var item = t.options.dropData.maps[i];
                    aDropData.push({id:item.model_id,name:item.model_name,data:item});
                }
            }
            var oDrop = new dayhrDropSelect({
                id: "download_excel_templates",
                width: 180,
                maxHeight: 250,
                data: aDropData,
                name: "modelId",
                onSelected:function(oSelect){
                    var _oData = oSelect.node.data
                    t.oCurrentSelection = _oData;//把当前选中的数据缓存起来
                    $(".base_import_infomation_show").text(_oData.model_instruction);

                    //是否导出已有数据
                    if(_oData.allow_export == 0){
                        t.setSwitchDisabled($('.operation_templates_description').eq(0),true);
                    }else{
                        t.setSwitchDisabled($('.operation_templates_description').eq(0),false);
                    }
                    //是否导出默认值  对应页面“是否导出已有数据”
                    if(_oData.export_default == 1){
                        $('#operation_templates').bootstrapSwitch("state",true);
                    }else{
                        $('#operation_templates').bootstrapSwitch("state",false);
                    }



                    //是否依据导入模板删除系统中已有的数据
                    if(_oData.allow_delete == 0){
                        t.setSwitchDisabled($(".upload_file_description").eq(0),true);
                    }else{
                        t.setSwitchDisabled($(".upload_file_description").eq(0),false);
                    }
                    //是否删除默认值
                    if(_oData.del_default == 1){
                        $("#base_uploadExcel_and_delete").bootstrapSwitch("state",true);
                    }else{
                        $("#base_uploadExcel_and_delete").bootstrapSwitch("state",false);
                    }



                    //是否覆盖导入
                    if(_oData.allow_update == 0){
                        t.setSwitchDisabled($(".upload_file_description2").eq(0),true);
                    }else{
                        t.setSwitchDisabled($(".upload_file_description2").eq(0),false);
                    }
                    //是否更改默认值
                    if(_oData.update_default == 1){
                        $("#base_uploadExcel_and_update").bootstrapSwitch("state",true);
                    }else {
                        $("#base_uploadExcel_and_update").bootstrapSwitch("state",false);
                    }

                }
            });
            t.oDrop = oDrop;
            if(aDropData.length){
                oDrop.setValue(aDropData[0].id);
            }
        },
        /**
         * 是否控件
         * */
        initSwitch:function(){
            $(".base_export_excel_switch").find(".switch-checkbox").bootstrapSwitch();

            //更新和删除只能有一个是选择“是”
            $('#base_uploadExcel_and_update').on('switchChange.bootstrapSwitch', function(event, state) {
                if(state){
                    $("#base_uploadExcel_and_delete").bootstrapSwitch("state",false);
                }
            });
            $('#base_uploadExcel_and_delete').on('switchChange.bootstrapSwitch', function(event, state) {
                if(state){
                    $("#base_uploadExcel_and_update").bootstrapSwitch("state",false);
                }
            });
        },
        /**
         * 设置是否框的可用状态
         * @flag  true/false
         * */
        setSwitchDisabled:function ($obj,flag) {
            var t = this;
            var sDisable = '<div class="base_switch_disable" style="width:100%;height: 100%;position: absolute;left:0;top:0;background: #fff;opacity: 0.5;"></div>';
            if(flag){
                $obj.find(".base_switch_disable").remove();
                $obj.append(sDisable);
            }else{
                $obj.find(".base_switch_disable").remove();
            }
        },
          /**
         * 格式验证
         * */
        fileCheck:function(str){
            if (str == "") {
                $("#upload_file_excel_input").val("");
                layer.msg("请上传一个Excel文件", {offset: 0,shift:6});
                return false;
            } else if (!/\.(xls|xlsx|XLS|XLSX)$/.test(str)) {
                layer.msg("文件类型必须是Excel文件类型", {offset: 0,shift:6});
                str = "";
                return false;
            }
            return true;
        },
        /**
         * 初始化上传
         * */
        initWebuploader:function(){
            var t = this;
            var oPostData = {infoSetId: t.infoSetId};
            var $form = $("#upload_file_excel_btns");
            var url = (gMain.apiBasePath?gMain.apiBasePath:gMain.basePath)+'route/'+t.infoSetId+'/importData.do';
            $form.attr("action",url);
            //如果是码表就多传一个参数ct_set_id
            if(t.options.oMetaData.options.infoSetId=="ct" && t.options.oMetaData.options.navigationId){oPostData.ct_set_id = t.options.oMetaData.options.navigationId;}
            //选择文件事件
            $("#upload_file_excel_file").change(function(){
                if(t.fileCheck($(this).val())){
                    $("#upload_file_excel_input").val($(this).val());
                }else{
                    $(this).val("");
                }
            });
            //上传按钮变色
            $("#upload_file_excel_file").hover(function(){
                $("#upload_file_excel_selectFile").css({background:"#2065ae"});
            },function(){
                $("#upload_file_excel_selectFile").css({background:"#36a3ff"});
            });
            //开始上传
            $("#upload_file_excel_startUpload").click(function(){
                if($("#upload_file_excel_file").val() == ""){
                    layer.msg("请先选择一个Excel文件", {offset: 0,shift:6});
                    return false;
                }
                $("#upload_file_btns_disabled").show(); //挡住屏蔽选择上传
                //loading
                t.loadingDialog =  dialog({
                    fixed: true,
                    content:'<div style="text-align:center;line-height: 25px;"><img src="'+gMain.basePath+'static/base/images/loading_rectangle.gif"><br/>正在检验数据及导入数据,请稍候...</div>'
                }).showModal();
                //模拟表单上传接口
                var sModelId = "";
                if(t.oDrop){
                    sModelId = t.oDrop.getValue();
                }
                oPostData.modelId = sModelId;
                oPostData.allowDelete =$("#base_uploadExcel_and_delete").bootstrapSwitch("state")?"1":"0";
                oPostData.allowUpdate =$("#base_uploadExcel_and_update").bootstrapSwitch("state")?"1":"0";

                //薪酬处理 特殊传参
                if(t.infoSetId == 'pay_payroll_list'){
                    t.options.customParam.payment_mark = '1';
                }
                if(!$.isEmptyObject(t.options.customParam)){
                    var sCustomParam = JSON.stringify(t.options.customParam);
                    oPostData.customParam= sCustomParam;
                }

                //html5上传方法
                var oFormData = new FormData();
                for(var i in oPostData){
                    oFormData.append(i, oPostData[i]);
                }
                oFormData.append('file', $('#upload_file_excel_file')[0].files[0]);
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: oFormData,
                    processData: false,  // 告诉jQuery不要去处理发送的数据
                    contentType: false  // 告诉jQuery不要去设置Content-Type请求头
                }).done(function(data){
                    t.loadingDialog && t.loadingDialog.close().remove(); //隐藏loading
                    var _html = "";
                    if(data.result == "true"){
                        if(data.failNum == "0" && data.successNum){
                            _html = '恭喜你全部导入成功，共导入数据'+data.successNum+'条<br/>';
                        }else{
                            _html = '<div style="display: inline;vertical-align: middle;color: red;">信息导入完成，成功<span style="color:#333;">'+data.successNum+'</span>条，失败'+data.failNum+'条</div>，<br/>继续操作请点击<a target="_blank"  class="flat-button flat-medium flat-blue" href="'+gMain.basePath+'route/'+t.infoSetId+'/downfilelog.do?fileName='+data.errorUrl+'">下载出错信息</a>';
                        }
                    }else if(data.result == "false"){
                        layer.msg(data.resultDesc, {offset: 0,shift:6}); //给个错误提示
                        //如果登陆会话已过期，就弹出登陆框
                        if(data.statusCode && data.statusCode == "50"){
                            Ajax.showLoginBox();
                        }
                    }else{
                        _html = "<div style='display: inline;vertical-align: middle;color: red;'>导入失败"+(data.resultDesc?"，"+data.resultDesc:"") + "</div><br/>";
                    }
                    _html += '<a href="javascript:void(0)" id="base_look_back" class="flat-button flat-medium flat-blue">返回查看</a><a href="javascript:void(0)" id="upload_again" class="flat-button flat-medium flat-blue">继续导入</a>';
                    $("#dayhr_import_complete").find("dd").html(_html); //显示完成结果

                    $("#base_look_back").off("click").on("click",function(){
                        t.d && t.d.close().remove();
                        t.options.mmg.load();
                        //如果是导入组织、导入职务类型，就更新数导航
                        if(t.infoSetId == "org_list" || t.infoSetId == "hr_job_family"){
                            t.options.oMetaData.quickMenuNav.updateTreeDataAndDom(); //重载树导航
                        }
                    });
                });

                return false;
            });

            //重新上传
            $("#dayhr_import_complete").on("click","#upload_again",function(){
                $("#upload_file_btns_disabled").hide(); //移除遮罩
                $("#dayhr_import_complete").find("dd").html(""); //清空完成结果
                $("#upload_file_excel_input,#upload_file_excel_file").val(""); //清空表单值
            });

        }


    };

    module.exports = Import;

});
